package com.atguigu.ggkt.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

public class Base64FileConversion {

    // 将文件转换为Base64编码的字符串
    public static String encodeFileToBase64(File file) throws IOException {
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            byte[] fileBytes = new byte[(int) file.length()];
            fileInputStream.read(fileBytes);
            return Base64.getEncoder().encodeToString(fileBytes);
        }
    }

    // 将Base64编码的字符串复原为文件
    public static void decodeBase64ToFile(String base64Str, File outputFile) throws IOException {
        byte[] decodedBytes = Base64.getDecoder().decode(base64Str);
        try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
            fileOutputStream.write(decodedBytes);
        }
    }

    public static void main(String[] args) {
        // 输入文件
        File inputFile = new File("E:\\ws07\\wechat-platform-certificate\\wechatpay_3BCDB0A058DE6C2D5BBBE5E5020AE87313106349.pem");
        // 输出文件
        File outputFile = new File("E:\\ws07\\wechat-platform-certificate\\wechatpay_3BCDB0A058DE6C2D5BBBE5E5020AE87313106349.pem2");

        try {
            // 将文件转换为Base64编码
            String encodedString = encodeFileToBase64(inputFile);
            System.out.println("Encoded String: " + encodedString);

            // 将Base64编码复原为文件
            decodeBase64ToFile(encodedString, outputFile);

            // 验证输出文件与输入文件是否一致
            boolean isEqual = org.apache.commons.io.FileUtils.contentEquals(inputFile, outputFile);
            System.out.println("Files are equal: " + isEqual);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}